package com.xiaoyu.lanling.feature.fate

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.feature.main.controller.MainActivityViewController
import com.xiaoyu.lanling.feature.view.StatusLayout
import com.xiaoyu.lanling.view.OnShowFragment

class MainFateWrapperFragment : OnShowFragment() {

    private lateinit var mRootView: StatusLayout
    private var mView: View? = null
    private var isInitIndex = false
    private var mController: MainFateWrapperController? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRootView = StatusLayout(AppContext.getContext())
        mRootView.layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
        return mRootView
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            val initIndex = it.getInt(Constant.PARAM_INDEX, -1)
            isInitIndex = initIndex == MainActivityViewController.MAIN_VIEW_PAGER_FATE
            if (isInitIndex) {
                tryToInit()
            }
        }
    }

    override fun onShowSafelyAfterAppFinishInit() {
        super.onShowSafelyAfterAppFinishInit()
        if (!isInitIndex) {
            tryToInit()
        }
    }

    private fun tryToInit() {
        if (activity == null) {
            return
        }

        if (mView == null) {
            mView = mRootView.showLazyViewWithLoading(layoutInflater, R.layout.fragment_main_fate_wrapper)
        }
        if (mController == null) {
            mController = MainFateWrapperController(this)
            mController?.onStart()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constant.RequestCode.LOCATION) {
            mController?.updatePermissionLayout()
            mController?.requestLocation()
        }
    }

    override fun onDetach() {
        super.onDetach()
        mController?.onDestroy()
    }
}